package com.simpleplayer.views.customview;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.simpleplayer.R;
import com.simpleplayer.services.NetWorkService;

import java.util.ArrayList;
import java.util.Objects;

public class CustomListDialog extends Dialog {

    private static final String THUMBMNAIL_THREAD_NAME = "thumbmnail-extract-thread";

    public interface OnItemClickListener {
        public void onClick(String displayContent, String Realcontent);
    }

    private final Context mContext;
    private final ArrayList<Item> mContents;
    private final Handler mMainHandler;

    private String mTitle;
    private ArrayList<OnItemClickListener> mOnItemClickListeners;

    public CustomListDialog(@NonNull Context context) {
        super(context);
        this.mContext = context;
        this.mContents = new ArrayList<Item>();
        this.mMainHandler = new Handler();
        this.mOnItemClickListeners = new ArrayList<>();
    }

    public CustomListDialog(@NonNull Context context, int themeResId) {
        super(context, themeResId);
        this.mContext = context;
        this.mContents = new ArrayList<Item>();
        this.mMainHandler = new Handler();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.custom_list_dialog);

        TextView titleView = (TextView) findViewById(R.id.list_dialog_title);
        View dividerView = (View) findViewById(R.id.list_dialog_divider);
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view);

        if (mTitle != null) {
            titleView.setVisibility(View.VISIBLE);
            dividerView.setVisibility(View.VISIBLE);
            titleView.setText(mTitle);
        }

        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        recyclerView.setAdapter(new CustomAdapter());
        DividerItemDecoration decoration = new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL);
        decoration.setDrawable(Objects.requireNonNull(ContextCompat.getDrawable(mContext, R.drawable.custom_divider)));
        recyclerView.addItemDecoration(decoration);
    }

    public void setTitle(String title) {
        this.mTitle = title;
    }

    /**
     * @param thumbnail 要显示的缩略图的 uri，thumbnail 为 null 时显示默认图片
     * @param displayContent 要显示的文字内容，不能为 null
     * @param realContent 真实内容，点击时回调参数，不能为 null
     */
    public void addItem(String thumbnail, @NonNull String displayContent, @NonNull String realContent) {
        mContents.add(new Item(thumbnail, displayContent, realContent));
    }

    public void addOnItemClickListener(OnItemClickListener listener) {
        mOnItemClickListeners.add(listener);
    }

    public void removeOnItemClickListener(OnItemClickListener listener) {
        mOnItemClickListeners.remove(listener);
    }

    private void onItemClick(ViewHolder holder) {
        String displayContent = mContents.get(holder.getLayoutPosition()).displayContent;
        String realContent = mContents.get(holder.getLayoutPosition()).realContent;
        for (OnItemClickListener l: mOnItemClickListeners) {
            l.onClick(displayContent, realContent);
        }
    }

    // 自定义适配器，用于自定义列表样式
    private class CustomAdapter extends RecyclerView.Adapter<ViewHolder> {

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.list_dialog_row_item, parent, false);

            return new ViewHolder(v);
        }

        @SuppressLint("ClickableViewAccessibility")
        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            if (mContents.get(position).thumbnail != null &&
                    !mContents.get(position).thumbnail.isEmpty()) {
                // 启动一个子线程进行获取做略图
                new Thread(() -> {
                    Bitmap thumbnail = NetWorkService.getURLImage(mContents.get(position).thumbnail);
                    if (thumbnail != null) {
                        // 返回主线程进行更新缩略图
                        mMainHandler.post(()-> {
                            holder.getThumbnailView().setImageDrawable(
                                    new BitmapDrawable(null, thumbnail));
                        });
                    }
                }, THUMBMNAIL_THREAD_NAME).start();
            }
            holder.getContentView().setText(mContents.get(position).displayContent);
            holder.getContentView().setOnClickListener(v -> CustomListDialog.this.onItemClick(holder));
        }

        @Override
        public int getItemCount() {
            return mContents.size();
        }
    }

    // 持有一行 view
    private static class ViewHolder extends RecyclerView.ViewHolder {
        private final ImageView thumbnailView;
        private final TextView contentView;

        public ViewHolder(View v) {
            super(v);
            this.thumbnailView = (ImageView) v.findViewById(R.id.thumbnail);
            this.contentView = (TextView) v.findViewById(R.id.display_content);
            this.contentView.setMovementMethod(ScrollingMovementMethod.getInstance());
        }

        public ImageView getThumbnailView() {
            return thumbnailView;
        }

        public TextView getContentView() {
            return contentView;
        }
    }

    // 保存一行条目信息的结构体
    private static class Item {
        public String thumbnail;
        public String displayContent;
        public String realContent;

        public Item(String thumbnail, String displayContent, String realContent) {
            this.thumbnail = thumbnail;
            this.displayContent = displayContent;
            this.realContent = realContent;
        }
    }
}
